/**
 * Description:
 *
 * @author      Eden
 * @datetime    2016/12/4 22:26
 * @copyright   Beijing CmsTop Technology Co.,Ltd.
 */

(function () {

    "use strict";

    var api = {
        saveThumbUrl: "/farm/base/upThumb?type=base&extra=slider",
        saveAddUrl: "/farm/base/doAdd",
        saveEditUrl: "/farm/base/doEdit",
        getStreamLists: '/stream/device/getAll',
        getDetail: '/farm/base/getDetail',
        deleteBaseUrl: '/farm/base/del'
    };

    sm.controller('admin-base-index', ['$scope', '$http', 'Modal', function ($scope, $http, Modal) {


        $scope.pageType = pageType;
        $scope.thumbView = "";
        $scope.error = "";
        $scope.detail = {
            'baseName': "",
            'thumb': "",
            'telephone': "",
            'charger': "",
            'phone': "",
            'address': "",
            'streamId': 0,
            'content': '',
            'email': "",
            'password': ''
        };
        $scope.streamLists = [];
        var ue = UE.getEditor('container', {
            'autoClearinitialContent' : false,
            'toolbars' : [['fullscreen', 'source', 'preview', '|', 'bold', 'italic', 'underline', '|',
                'justifyleft', 'justifycenter', 'justifyright', '|', 'insertorderedlist', 'insertunorderedlist', 'blockquote', 'emotion',
                'link', 'removeformat', 'simpleupload', 'insertimage', '|', 'paragraph', 'fontsize',
                'inserttable']],
            'elementPathEnabled' : false,
            'initialFrameHeight': 250,
            'focus' : false,
            'maximumWords' : 999999,
            'zIndex': 999
        });

        // =============================================
        var $ = jQuery, uploader;

        // 初始化Web Uploader
        uploader = WebUploader.create({
            auto: true,
            server: api.saveThumbUrl,
            pick: '#uploadImage',
            duplicate: true,
            accept: {
                title: 'Images',
                extensions: 'gif,jpg,jpeg,png'
            }
        });

        uploader.on( 'uploadSuccess', function(file, res) {
            if (res.state) {
                $scope.detail.thumb = res.data.key;
                var b = res.data.url;
                $scope.thumbView = b || '';
                $scope.$apply();
            } else {
                var error = res.error ? res.error : '上传失败';
                Modal.error(error);
            }
        });

        // ===========end==================================

        $scope.deleteBase = function (baseId) {
            Modal.alert({
                title: "操作提示",
                content: "您确定要删除该供应商吗？",
                buttons:[{
                    name: "取消"
                }, {
                    name: "确定删除",
                    event: function () {
                        doDelete(baseId);
                    }
                }]
            });
        };

        function doDelete(baseID) {
            $http.post(api.deleteBaseUrl, {
                id: baseID
            }).success(function (res) {
                if (res.state) {
                    location.href = '/farm/base/index';
                } else {
                    Modal.error('删除失败');
                }
            });
        }

        // 保存数据
        $scope.saveBase = function () {
            var html = ue.getContent();
            $scope.detail['content'] = html;

            if ($scope.selectVideo && $scope.stream.streamId) {
                $scope.detail['streamId'] = $scope.stream.streamId;
            }

            // 验证数据
            if (!checkParams()) {
                Modal.alert($scope.error);
                return false;
            }

            var url = $scope.pageType == 'edit' ? api.saveEditUrl : api.saveAddUrl;
            $http.post(url, $scope.detail).success(function (res) {
                if (res.state) {
                    if ($scope.pageType == 'add') {
                        afterAdd();
                    } else {
                        Modal.success('修改成功');
                    }
                } else {
                    var error = res.error ? res.error : '编辑失败';
                    Modal.error(error);
                }
            });

        };

        function afterAdd() {
            Modal.success({
                title: '基地创建成功',
                buttons: [{
                    'name': '返回列表',
                    'event': function () {
                        window.history.back();
                    }
                }, {
                    'name': '继续添加',
                    'event': function () {
                        $scope.detail = {
                            'baseName': "",
                            'thumb': "",
                            'telephone': "",
                            'charger': "",
                            'phone': "",
                            'address': "",
                            'streamId': null,
                            'content': '',
                            'email': "",
                            'password': ""
                        };
                        $scope.stream = {
                            'streamId': 0,
                            'deviceName': '----请选择----',
                            'videoUrlHD': '',
                            'videoUrlSD': ''
                        };
                        $scope.thumbView = "";
                        $scope.selectVideo = false;
                        ue.setContent('');
                    }
                }]
            });
        }

        function checkParams() {

            var detail = $scope.detail;
            if (!detail.email) {
                $scope.error = "管理员邮箱不能为空";
                return false;
            }

            if (!detail.password || detail.password.length < 6) {
                $scope.error = "密码不能小于6位";
                return false;
            }

            if (!detail.baseName) {
                $scope.error = "基地名称不能为空";
                return false;
            }

            if (!detail.charger) {
                $scope.error = "基地负责人姓名不能为空";
                return false;
            }

            if (detail.telephone && !/^0\d{2,3}-?\d{7,8}$/.test(detail.telephone)
                && !/^400-([0-9]){1}([0-9-]{7})$/.test(detail.telephone)) {
                $scope.error = "电话号码格式错误";
                return false;
            }

            if (!detail.phone) {
                $scope.error = "手机号不能为空";
                return false;
            }

            if (!detail.address) {
                $scope.error = "基地地址不能为空";
                return false;
            }

            if (!detail.thumb) {
                $scope.error = "请上传缩略图";
                return false;
            }

            if (detail.phone && !/^1[34578]\d{9}$/.test(detail.phone)) {
                $scope.error = "手机号格式错误";
                return false;
            }

            if ($scope.selectVideo && !detail.streamId) {
                $scope.error = '视频流错误';
                return false;
            }

            if (!detail.content) {
                $scope.error = '基地介绍不能为空';
                return false;
            }

            return true;
        }


    }]);

})();